<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="合并SPU"
    width="820"
    draggable
    @close="close"
    :z-index="2000"
  >
    <div class="mb-2">已选择SPU: {{ tableData.length }}条</div>
    <div class="mb-4">
      <vxe-table
        show-overflow
        :data="tableData"
        :column-config="{ resizable: true }"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        height="400"
      >
        <vxe-column field="" title="主属性" width="120">
          <template #default="{ row, rowIndex }">
            <el-radio
              v-model="main_spu_id"
              size="large"
              :label="row.spu_id"
              :name="row.spu_id"
              @click.prevent="radioChange($event, row)"
              >主属性</el-radio
            >
          </template>
        </vxe-column>
        <vxe-column field="spu" title="SPU" width="200"></vxe-column>
        <vxe-column field="spu_cn_title" title="产品名称"></vxe-column>
      </vxe-table>
    </div>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <AddSKU ref="addSKURef" @assign="assign"></AddSKU>
</template>
<script setup name="mergeSPU">
import { reactive, toRefs } from "vue";
import { mergeSPU } from "../api/index";
import AddSKU from "./AddSKU.vue";
import { ElMessage } from "element-plus";
const data = reactive({
  visible: false,
  loading: false,
  tableData: [],
  main_spu_id: "",
  load: false,
});
const { visible, loading, tableData, main_spu_id, load } = toRefs(data);

const open = async (records) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  tableData.value = records;
  visible.value = true;
};
const close = () => {
  main_spu_id.value = "";
  visible.value = false;
};

const addSKURef = ref();
const addSKU = () => {
  nextTick(() => {
    addSKURef.value.open();
  });
};

const assign = (val) => {
  tableData.value = val;
};

const radioChange = (val, row) => {
  main_spu_id.value = row.spu_id;
};

const save = async () => {
  if (!main_spu_id.value) {
    ElMessage.error("请选择合并后的SPU");
    return;
  }
  try {
    const res = await mergeSPU({
      main_spu_id: main_spu_id.value,
      merge_spu_ids: tableData.value.map((i) => i.spu_id),
    });
    ElMessage.success(res.message);
    close();
  } catch (e) {
    throw Error(e);
  }
};

defineExpose({ open });
</script>
